export class ResourceManager {

    textCache: { [url: string]: string } = {};
    imageCache: { [url: string]: HTMLImageElement } = {};
    soundCache: { [url: string]: HTMLAudioElement } = {};

    loadImage(url: string) {
        return new Promise<void>((resolve, reject) => {
            const img = document.createElement('img');
            img.src = url;
            img.onload = () => {
                this.imageCache[url] = img;
                resolve();
            }
        })

    }
    loadsound(url: string) {
        return new Promise<void>((resolve, reject) => {
            const sound = new Audio();
            sound.src = url;
            sound.load();
            // sound.onload = () => {
            //     console.log("onload sound")
            //      this.soundCache[url] = sound;
            //      resolve();
            //  }
            //Audio好像不能执行onload方法，用onload总是会卡在这，直接加载不知到会不会有问题
             this.soundCache[url] = sound;
             resolve();
        })

    }

    loadText(url: string) {
        return new Promise<void>((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.open('get', url);
            xhr.send();
            xhr.onload = () => {
                this.textCache[url] = xhr.responseText;
                resolve();
            }
        })

    }

    getText(url: string) {
        const text = this.textCache[url];
        if (!text) {
            alert('配置文件加载失败' + url)
        }
        return text;
    }

    getImage(url: string) {
        const image = this.imageCache[url]
        if (!image) {
            alert('图片加载失败' + url)
        }
        return image;
    }
    getSound(url: string) {
        const sound = this.soundCache[url]
        if (!sound) {
            alert('音乐加载失败' + url)
        }
        return sound;
    }
}